#pragma once

#include <sys/select.h>
#include <memory>
#include "Socket.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include "Common.hpp"

using namespace LogModule;
using namespace SocketModule;

class SelectServer
{
    static const int size = 1024;
    static const int defaultfd = -1;

public:
    SelectServer(const InetAddr &addr)
        : _listensock(std::make_unique<TCPSocket>(addr, Type::SERVER)),
          _isrunning(false)
    {
        // 初始化辅助数组
        for (int i = 0; i < size; i++)
        {
            _fdarray[i] = defaultfd;
        }
        // 把监听fd入数组
        _fdarray[0] = _listensock->Fd();
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            PrintFd();
            // 不能直接accept，等待的事情交给select
            fd_set rfds;
            FD_ZERO(&rfds);
            int maxfd = -1;
            for (int i = 0; i < size; i++)
            {
                if (_fdarray[i] != defaultfd)
                {
                    FD_SET(_fdarray[i], &rfds);
                }
                if (maxfd < _fdarray[i])
                    maxfd = _fdarray[i];
            }
            struct timeval timeout;
            timeout.tv_sec = timeout.tv_usec = 1;
            // select，等待多个读fd
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);
            switch (n)
            {
            case 0:
                LOG(LogLevel::INFO) << "select超时了";
                break;
            case -1:
                LOG(LogLevel::ERROR) << "select error";
                break;
            default:
                Dispatch(&rfds); // 等待成功，将等待结果rfds处理
                break;
            }
        }
        _isrunning = false;
    }

    // 派遣任务
    void Dispatch(fd_set *rfds)
    {
        // rfds: 0001 1000(读事件就绪，派发任务)
        for (int pos = 0; pos < size; pos++)
        {
            if (_fdarray[pos] == defaultfd)
                continue;
            // 1.取出读就绪的fd
            if (FD_ISSET(_fdarray[pos], rfds))
            {
                // listenfd读就绪
                if (_fdarray[pos] == _listensock->Fd())
                    Accept();
                // 普通sockfd读就绪
                else
                    Recv(pos);
            }
        }
    }

    // 获取连接
    void Accept()
    {
        InetAddr addr;
        int sockfd = _listensock->Accept(&addr); // 一定不会阻塞，因为读事件已经就绪
        if (sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "accept error";
            exit(ACCEPT_ERR);
        }
        else
        {
            // 连接获取成功，找一个空位，添加
            int pos = 0;
            for (; pos < size; pos++)
            {
                if (_fdarray[pos] == defaultfd)
                    break;
            }
            if (pos == size)
            {
                // 满了
                LOG(LogLevel::WARNING) << "_fdarray is full";
                close(sockfd);
            }
            else
            {
                _fdarray[pos] = sockfd;
                LOG(LogLevel::INFO) << "add sockfd to _fdarray, fd: " << sockfd;
            }
        }
    }

    void Recv(int pos)
    {
        int sockfd = _fdarray[pos];
        char buff[1024];
        ssize_t n = read(sockfd, buff, sizeof(buff) - 1);
        if (n < 0)
        {
            LOG(LogLevel::WARNING) << "read error";
            // 1.移除_fdarray中的sockfd
            _fdarray[pos] = defaultfd;

            // 2.关闭连接sockfd，防止文件描述符泄漏
            close(sockfd);
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "client exit, remove fd from _fdarray: " << sockfd;
            // 1.移除_fdarray中的sockfd
            _fdarray[pos] = defaultfd;

            // 2.关闭连接sockfd，防止文件描述符泄漏
            close(sockfd);
        }
        else
        {
            // 读到了数据
            buff[n] = 0;
            std::cout << "client says@ " << buff;
        }
    }

    void PrintFd()
    {
        std::cout << "_fdarray[]: ";
        for (int i = 0; i < size; i++)
        {
            if (_fdarray[i] == defaultfd)
                continue;
            std::cout << _fdarray[i] << " ";
        }
        std::cout << std::endl;
    }

    void Stop()
    {
        _isrunning = false;
    }
    ~SelectServer()
    {
        _listensock->Close();
    }

private:
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;
    int _fdarray[size];
};